package com.test.qpbgboot.show.service.impl;

import com.test.qpbgboot.base.exception.ServiceException;
import com.test.qpbgboot.base.response.ResultStatus;
import com.test.qpbgboot.base.utils.BaseUtils;
import com.test.qpbgboot.evaluation.mapper.OrderEvaluationMapper;
import com.test.qpbgboot.show.mapper.RoomMapper;
import com.test.qpbgboot.show.mapper.ShopMapper;
import com.test.qpbgboot.show.mapper.TagMapper;
import com.test.qpbgboot.show.pojo.dto.RoomQuery;
import com.test.qpbgboot.show.pojo.dto.RoomSaveParam;
import com.test.qpbgboot.show.pojo.dto.ShopQuery;
import com.test.qpbgboot.show.pojo.entity.Room;
import com.test.qpbgboot.show.pojo.vo.RoomVO;
import com.test.qpbgboot.show.pojo.vo.ShopVO;
import com.test.qpbgboot.show.service.RoomService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Service
@Slf4j
@Transactional(rollbackFor = Exception.class)
public class RoomServiceImpl implements RoomService {

    @Value("${aliyun.oss.bucket-url}")
    private String bucketUrl;
    @Autowired
    private RoomMapper roomMapper;
    @Autowired
    private OrderEvaluationMapper orderEvaluationMapper;
    @Autowired
    private ShopMapper shopMapper;
    @Autowired
    private TagMapper tagMapper;

    @Override
    public List<RoomVO> roomSelect(RoomQuery roomQuery) {
        log.debug("房间查询业务，参数:{}", roomQuery);
        List<RoomVO> roomVOList = roomMapper.selectRoomVObyRoomQuery(roomQuery);
        if (roomVOList != null && !roomVOList.isEmpty()) {
            for (RoomVO roomVO : roomVOList) {
                additionalField(roomVO);
            }
        }
        log.debug("房间查询结果:{}", roomVOList);
        return roomVOList;
    }

    @Override
    public void roomSave(RoomSaveParam roomSaveParam) {
        log.debug("房间保存业务，参数:{}", roomSaveParam);
        Room room = new Room();
        BeanUtils.copyProperties(roomSaveParam, room);

        List<String> status = Arrays.asList("1", "0");
        if (!status.contains(room.getVisible())) {
            throw new ServiceException(ResultStatus.ILLEGAL_ARGUMENT,"是否展示设置错误");
        }

        if (room.getVisible().equals("1") && room.getPrice() == null) {
            throw new ServiceException(ResultStatus.ILLEGAL_ARGUMENT,"展示的房间价格不能为空");
        }

        ShopQuery shopQuery = new ShopQuery();
        shopQuery.setId(room.getShopId());
        List<ShopVO> shopVOList = shopMapper.selectShopVObyShopsQuery(shopQuery);
        if (shopVOList == null || shopVOList.isEmpty()) {
            throw new ServiceException(ResultStatus.INVALID_ID,"店家id无效");
        }

        List<Long> tagIdList = roomSaveParam.getTagIdList();
        if (tagIdList != null && !tagIdList.isEmpty()) {
            if (tagIdList.size() != tagMapper.selectCountByIdList(tagIdList)) {
                throw new ServiceException(ResultStatus.INVALID_ID, "标签id无效或重复");
            }
            String tagIds = tagIdList.stream().filter(Objects::nonNull)
                    .map(String::valueOf).collect(Collectors.joining(","));
            room.setTagIds(tagIds);
        }

        List<String> imgUrlList = roomSaveParam.getImgUrlList();
        String imgsUrl = BaseUtils.imgListToString(imgUrlList);
        imgsUrl = imgsUrl.replaceAll(bucketUrl, "bucketUrl");
        room.setImgsUrl(imgsUrl);

        if (room.getId() == null) {
            roomMapper.insert(room);
        } else {
            roomMapper.update(room);
        }
    }

    @Override
    public void roomDelete(Long roomId) {
        log.debug("房间删除业务，参数:{}", roomId);
        roomMapper.deleteById(roomId);
    }

    @Override
    public void roomInvisibledByShopId(Long shopId) {
        log.debug("更新-指定店家的房间为不可见-业务，参数:{}", shopId);
        roomMapper.updateInvisibleByShopId(shopId);
    }

    private void additionalField(RoomVO roomVO) {
        String tagIds = roomVO.getTagIds();
        if (tagIds != null && !tagIds.isEmpty()) {
            List<Long> tagIdList = Arrays.stream(tagIds.split(","))
                    .map(Long::parseLong).collect(Collectors.toList());
            roomVO.setTagIdList(tagIdList);
        }else{
            roomVO.setTagIdList(new ArrayList<>());
        }
        String imgsUrl = roomVO.getImgsUrl();
        imgsUrl = imgsUrl.replaceAll("bucketUrl", bucketUrl);
        List<String> imgUrlList = BaseUtils.imgStringToList(imgsUrl);
        roomVO.setImgUrlList(imgUrlList);
        Double aDouble = orderEvaluationMapper.selectAvgRatingByRoomId(roomVO.getId());
        roomVO.setAvgRating( aDouble!=null ? aDouble: (double) 0);
    }
}
